/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2022-09-23 16:33:50
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2022-10-12 16:22:05
 * @FilePath: /vue3-datav/src/router/index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory } from 'vue-router';
import { getToken } from '@/utils/auth';

const router = createRouter({
    // history: createWebHistory(import.meta.env.BASE_URL),
    history: createWebHashHistory(),
    scrollBehavior: () => ({ top: 0 }),
    routes: [
        {
            path: '/auth/login',
            component: () => import('../views/auth/LoginView.vue'),
            meta: {
                title: '登录'
            }
        },
        {
            path: '/template',
            component: () => import('../views/template/IndexView/index.vue'),
            meta: {
                title: '模板首页'
            }
        },
        {
            path: '/401',
            component: () => import('../views/error/401.vue'),
            meta: {
                title: '无权访问'
            }
        },
        {
            path: '/:catchAll(.*)',
            component: () => import('../views/error/404.vue'),
            meta: {
                title: '不存在'
            }
        }
    ]
});

const whiteList = ['/auth/login', '/template'];
router.beforeEach((to, from, next) => {
    if (typeof to.meta.title === 'string') {
        // 设置名称
        document.title = to.meta.title;
    }
    if (getToken() || whiteList.includes(to.path)) {
        next();
    } else {
        next(`/auth/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
    }
});

export default router;
